﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace produccion.forms
{
    /// <summary>
    /// Lógica de interacción para FRMmanalmmat.xaml
    /// </summary>
    public partial class FRMmanalmmat : Window
    {
        manalmmat _manalmmat;

        public FRMmanalmmat()
        {
            InitializeComponent();
            _manalmmat = (manalmmat)this.DataContext;
        }
   
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _manalmmat.listaAlmMat();
            limpiar();
            Keyboard.Focus(texCod);
        }

        private void limpiar() {
            texCod.Text = "";
            texNom.Text = "";
            _manalmmat.txtAlmMat.CAMBIO = false;
        }

        string camb;
        private void texCod_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_manalmmat.txtAlmMat.CODALM_ALM != camb)
            {
                if (_manalmmat.txtAlmMat.CAMBIO)
                {
                    if (MessageBox.Show("¿Está seguro que desea cambiar de elemento? se perderán los cambios no guardados.", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)//RRR
                    {
                        _manalmmat.txtAlmMat.CODALM_ALM = camb;
                        return;
                    }
                    _manalmmat.txtAlmMat.CAMBIO = false;
                }
                camb = _manalmmat.txtAlmMat.CODALM_ALM;
                _manalmmat.txtAlmMat.consultar();
                if (!_manalmmat.txtAlmMat.EXISTE)
                {
                    texNom.Text = "";
                    _manalmmat.txtAlmMat.CAMBIO = false;
                }
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_manalmmat.txtAlmMat.CAMBIO)
            {
                if (MessageBox.Show("¿Está seguro que desea salir? se perderán los cambios no guardados.", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)
                {
                    e.Cancel = true;
                }
                else{
                _manalmmat.txtAlmMat.CAMBIO = false;
                }
            }
        }

        private void butNue_Click(object sender, RoutedEventArgs e)
        {
            if (_manalmmat.txtAlmMat.CAMBIO)
            {
                if (MessageBox.Show("¿Está seguro que desea crear un nuevo elemento? se perderán los cambios no guardados.", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)//RRR
                {
                    return;
                }
                _manalmmat.txtAlmMat.CAMBIO = false;
            }
            limpiar();
            texCod.Focus();
            texCod.Select(0,0);
        }

        private void butSal_Click(object sender, RoutedEventArgs e)
        {
              this.Close();
        }
        
        private void butEli_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("¿Esta seguro que desea eliminar el elemento?", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel) {
                return;
            }
            _manalmmat.eliminar(wPnot);

            _manalmmat.listaAlmMat();
            limpiar();

            texCod.Focus();
            texCod.Select(0, 0);
        }

        private void butGua_Click(object sender, RoutedEventArgs e)
        {
            _manalmmat.guardar(wPnot);

            _manalmmat.listaAlmMat();
            limpiar();
            
            texCod.Focus();
            texCod.Select(0, 0);
        }

        private void cm_Closed(object sender, RoutedEventArgs e)
        {
            _manalmmat.filtrar();
        }

        private void quiFil_Click(object sender, RoutedEventArgs e)
        {
            _manalmmat.quiFil();
        }

        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
                if (_manalmmat.txtAlmMat.CAMBIO)
                {
                    if (MessageBox.Show("¿Está seguro que desea cambiar de elemento? se perderán los cambios no guardados.", "Confirmar", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)//RRR
                    {
                       return;
                    }
                    _manalmmat.txtAlmMat.CAMBIO = false;
                }
                if (_manalmmat.selAlmMat != null)
                {
                    _manalmmat.txtAlmMat.CODALM_ALM = _manalmmat.selAlmMat.CODALM_ALM;
                    _manalmmat.txtAlmMat.EXISTE = true;
                }
        }

        private void dataGrid1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.Enter && elemento != null)
            {
                e.Handled = true;
                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }

        //
        // SINGLE CLICK EDITING
        //
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
            {
                if (!cell.IsFocused)
                {
                    cell.Focus();
                }
                DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                if (dataGrid != null)
                {
                    if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                    {
                        if (!cell.IsSelected)
                            cell.IsSelected = true;
                    }
                    else
                    {
                        DataGridRow row = FindVisualParent<DataGridRow>(cell);
                        if (row != null && !row.IsSelected)
                        {
                            row.IsSelected = true;
                        }
                    }
                }
            }
        }

        static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.F3 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta == true) { MDOgeneral.logBusquedadAbierta = false; }
            }

            if (e.Key == Key.F4 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta1 == true) { MDOgeneral.logBusquedadAbierta1 = false; }
            }

            if (e.Key == Key.F5 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta2 == true) { MDOgeneral.logBusquedadAbierta2 = false; }
            }
        } 
    }

    internal class manalmmat : ObservableObject
    {

        #region propiedades

        private string _strTituloVentana;
        public string strTituloVentana
        {
            get { return _strTituloVentana; }
            set { _strTituloVentana = value; RaisePropertyChangedEvent("strTituloVentana"); }
        }

        private clases.CLSMAEALM _txtAlmMat = new clases.CLSMAEALM();
        public clases.CLSMAEALM txtAlmMat {
            get { return _txtAlmMat; } 
            set { _txtAlmMat = value;
            RaisePropertyChangedEvent("txtAlmMat");
            }
        }

        private clases.CLSMAEALM _filAlmMat = new clases.CLSMAEALM {CODALM_ALM="",NOMALM_ALM=""};
        public clases.CLSMAEALM filAlmMat
        {
            get { return _filAlmMat; }
            set
            {
                _filAlmMat = value;
                RaisePropertyChangedEvent("filAlmMat");
            }
        }

        private clases.CLSMAEALM _selAlmMat = new clases.CLSMAEALM();
        public clases.CLSMAEALM selAlmMat
        {
            get { return _selAlmMat; }
            set
            {
                _selAlmMat = value;
                RaisePropertyChangedEvent("selAlmMat");
             
            }
        }

        private List<clases.CLSMAEALM> _lisAlmMat = new List<clases.CLSMAEALM>();
        public List<clases.CLSMAEALM> lisAlmMat
        {
            get { return _lisAlmMat; }
            set
            {
                _lisAlmMat = value;
                RaisePropertyChangedEvent("lisAlmMat");
            }
        }

        private List<clases.CLSMAEALM> _lisFilAlmMat = new List<clases.CLSMAEALM>();
        public List<clases.CLSMAEALM> lisFilAlmMat
        {
            get { return _lisFilAlmMat; }
            set
            {
                _lisFilAlmMat = value;
                RaisePropertyChangedEvent("lisFilAlmMat");
            }
        }

        #endregion

        #region metodos

        public manalmmat()
        {
            MDOgeneral.conectar();
            strTituloVentana = "Almacenes de materia prima - Usuario:" + MDOgeneral.usuario + " - [FRMmanalmmat]";
        }

        public void listaAlmMat()
        {
            try
            {
                lisAlmMat = selAlmMat.listaAlmMat();
                lisFilAlmMat = lisAlmMat;
            }
            catch (Exception ex) {MessageBox.Show(ex.Message);}
        }
        
        public void guardar(WrapPanel wPnot)
        {
            try
            {

                if (txtAlmMat.EXISTE)
                {
                    if (txtAlmMat.actualizar() > 0)
                    {
                        txtAlmMat.CAMBIO = false;
                        lisAlmMat.Clear();
                        lisAlmMat = txtAlmMat.listaAlmMat();
                        filtrar();
                        new MDOgeneral.notificar(wPnot, "Los cambios fueron guardados satisfactoriamente.", true);
                    }
                    else
                    {
                        new MDOgeneral.notificar(wPnot, "Los cambios no pueden ser guardados.", false);
                    }
                }
                else
                {
                    if (txtAlmMat.insertar() > 0)
                    {
                        txtAlmMat.CAMBIO = false;
                        txtAlmMat.EXISTE = true;
                        lisAlmMat.Clear();
                        lisAlmMat = txtAlmMat.listaAlmMat();
                        filtrar();                       
                        new MDOgeneral.notificar(wPnot, "El elemento fue creado satisfactoriamente.", true);
                    }
                    else
                    {
                        new MDOgeneral.notificar(wPnot, "El elemento no puede ser creado.", false);
                    }
                }

            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
        
        public void eliminar(WrapPanel wPnot)
        {
            try
            {
                if (txtAlmMat.eliminar() > 0)
                {
                    txtAlmMat.CAMBIO = false;
                    lisAlmMat.Clear();
                    lisAlmMat = txtAlmMat.listaAlmMat();
                    filtrar();
                    new MDOgeneral.notificar(wPnot, "El elemento ha sido eliminado satisfactoriamente.", true);
                }
                else
                {
                    new MDOgeneral.notificar(wPnot, "El elemento no puede ser eliminado.", false);
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }     
        }

        public void filtrar() {
            //lisFilAlmMat = lisAlmMat.FindAll(r => 
            //    r.CODALM_ALM.ToUpper().Contains(filAlmMat.CODALM_ALM.ToUpper()) &
            //    r.NOMALM_ALM.ToUpper().Contains(filAlmMat.NOMALM_ALM.ToUpper()) 
            // );
            //lisFilAlmMat.Add(new clases.CLSMAEALM { CODALM_ALM = "", NOMALM_ALM = ""});
        }

        public void quiFil()
        {
            filAlmMat = new clases.CLSMAEALM { CODALM_ALM = "", NOMALM_ALM = ""};
            lisFilAlmMat = lisAlmMat.FindAll(r => r.CODALM_ALM.ToUpper().Contains(filAlmMat.CODALM_ALM) & r.NOMALM_ALM.ToUpper().Contains(filAlmMat.NOMALM_ALM));
        }
        
        #endregion

    }
}
